from django.shortcuts import render
from rest_framework.views import APIView
from .models import User
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from .serializers import CreateUserSerializer
from rest_framework.permissions import IsAuthenticated
from django.core.mail import send_mail
# Create your views here.
# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView
class RegisterUsernameView(APIView):

    """
    判断用户是否注册

    GET     /users/usernames/(?P<username>\w{5,20})/count/

    POST    序列化器

    我们需要把用户名发送过来, 接收用户,根据用户名进行判断
    用户是否注册


    """

    def get(self,request,username):

        # 通过用户名的个数
        count = User.objects.filter(username=username).count()
        # 组织数据,返回
        context = {
            'count':count,
            'username':username #可选
        }

        return Response(context)


class RegisterMobileView(APIView):
    """
    GET    /users/phones/(?P<mobile>1[345789]\d{9})/count/

    GET   /users/phones/?mobile=xxxxxx
    POST   /users/phones    mobile=xxxx
    根据用户提交的手机号，判断是否存在该手机
    """

    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile)

        context = {
            'count':count,
            'mobile':mobile
        }
        return Response(context)


class CreateUserView(CreateAPIView):
    """实现注册功能
        1.对用户名，密码，手机号，短信验证码，是否同意协议  post给我们
        2.对数据进行验证
        3.验证之后，数据入库
    """
    serializer_class = CreateUserSerializer



#用户中心==个人信息
class UserCenterInfoView(APIView):
    """
    GET   /users/infos/
    只有登陆用户可以访问
    """
    permission_classes = [IsAuthenticated]


    def get(self,request):

        serializer = CreateUserSerializer(request.user)

        return Response(serializer.data)


from rest_framework.generics import UpdateAPIView
from .serializers import EmailSerializer

class EmailView(UpdateAPIView):
    """
    1.当用户点击确定按钮的时候，把邮箱发送给后台，邮箱需要校验
    2.更新用户的邮箱信息
    3.发送一个激活邮件
    4.激活链接应该如何实现
    5.邮件如何发送（代码怎么实现）
    6.邮件采用celery异步发送
    """
    from django.core.mail import send_mail
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):

        return self.request.user

from rest_framework import status

class EmailVerifiView(APIView):

    def get(self,request):
        #1.获取激活token，判断token是否存在
        token = request.query_params.get('token')
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        #2.对token进行校验
        user = User.check_verify_token(token)
        if user is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        #3.改变用户的邮件激活状态
        user.email_active = True
        user.save()

        return Response({'message':'ok'})